package fun.lifepoem.blog.filter;

import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class HeaderFilter implements AsyncHandlerInterceptor {

    private static final String TRACE_ID = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(TRACE_ID);
        if (StringUtils.hasText(traceId)) {
            MDC.put(TRACE_ID, traceId);
        } else {
            MDC.put(TRACE_ID, UUID.randomUUID().toString().replace("-", "").toUpperCase());
        }
        return true;
    }
}
